#include "opencvview.h"

opencvView::opencvView(QWidget *parent) :
    QWidget(parent)
{
    setFixedSize(1200,600);
    image = new QImage(geometry().width(),geometry().height(),QImage::Format_RGB888);
    this->show();
}

opencvView::~opencvView()
{
    delete image;
}

void opencvView::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);
    painter.drawImage(QPoint((geometry().width()-image->width())/2,(geometry().height()-image->height())/2),*image);
}

void opencvView::OpencvPaint(Mat &cvImg)
{
    QImage qImg = Mat2QImage(cvImg);
    *image = qImg.scaled(geometry().width(),geometry().height(),Qt::KeepAspectRatio);
    update();
}

QImage opencvView::Mat2QImage(Mat &cvImg)
{
    QImage qImg;
    QImage::Format format = QImage::Format_RGB888;
    if(cvImg.channels()==3)//3 channels color image
        cvtColor(cvImg,cvImg,CV_BGR2RGB);
    else if(cvImg.channels()==1)//grayscale image
        format = QImage::Format_Indexed8;
    qImg = QImage((const uchar*)(cvImg.data),cvImg.cols,cvImg.rows,cvImg.cols*cvImg.channels(), format);
    return qImg;
}

Mat opencvView::QImage2Mat(QImage &qImg)
{
    Mat cvImg;
    int format = CV_8UC3;
    switch(qImg.format())
    {
    case QImage::Format_ARGB32:
    case QImage::Format_RGB32:
    case QImage::Format_ARGB32_Premultiplied:
        format = CV_8UC4;
        break;
    case QImage::Format_RGB888:
        cvtColor(cvImg, cvImg, CV_BGR2RGB);
        break;
    case QImage::Format_Indexed8:
        format = CV_8UC1;
        break;
    default:break;
    }
    cvImg = Mat(qImg.height(), qImg.width(), format, (void*)qImg.bits(), qImg.bytesPerLine());
    return cvImg;
}

